package com.example.questionnaire.controller;



import com.example.questionnaire.dao.AllQuestionMapper;
import com.example.questionnaire.dao.QuestionnaireMapper;
import com.example.questionnaire.exception.RException;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.property.TextAlignment;
import org.json.JSONObject;
import com.example.questionnaire.common.ServerResponse;
import com.example.questionnaire.pojo.DAO.UserAnswerDataEncapsulationDAO;
import com.example.questionnaire.service.UserAnswerService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

import static com.example.questionnaire.util.CommonUtil.createCell;

@Controller
@RequestMapping("/pdf")
@Api(tags = "pdf")
public class PdfExportController {

    @Autowired
    private QuestionnaireMapper questionnaireMapper;

    @Autowired
    private AllQuestionMapper allQuestionMapper;
    @Autowired
    private UserAnswerService userAnswerService;

    @GetMapping("/export")
    @ApiOperation(value = "pdf导出", response = ServerResponse.class, httpMethod = "GET")
    @Transactional(rollbackFor = {Exception.class, RuntimeException.class, RException.class})
    public void exportPdf(HttpServletResponse response ,@RequestParam String formid) throws IOException{
        List<UserAnswerDataEncapsulationDAO> questionList = userAnswerService.statistics(formid);
        // 设置响应头信息
        response.setContentType("application/pdf");
        String questionnaireNames = questionnaireMapper.selectQuestionnaireName(formid);
        //获取当前时间
        LocalDateTime currentDateTime = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd ");
        String formattedDateTime = currentDateTime.format(formatter);
        //给PDF命名
        String formid_deta = formattedDateTime + "    " + formid + ".pdf";
        response.setHeader("Content-Disposition", "attachment; filename=" +  formid_deta);
        // 创建PDF文档
        PdfWriter writer = new PdfWriter(response.getOutputStream());
        PdfFont font = PdfFontFactory.createFont("STSong-Light","UniGB-UCS2-H");
        PdfDocument pdf = new PdfDocument(writer);
        Document document = new Document(pdf);
        document.setFont(font);
        Paragraph title1 = new Paragraph(questionnaireNames).setTextAlignment(TextAlignment.CENTER).setFontSize(25);
        document.add(title1);
        int count = 0;
        // 遍历问题列表
        for (UserAnswerDataEncapsulationDAO question : questionList) {
            ++ count;
            // 添加题目标题
            Paragraph title = new Paragraph("第" + count +"题:" + question.getTitle() + ":").setTextAlignment(TextAlignment.LEFT).setFontSize(15);
            document.add(title);
            // 创建表格
            Table table = new Table(2);
            table.setWidth(500);
            if(allQuestionMapper.selectAllByQuestionType(question.getSubjectId()) == 3){
                // 添加表头
                table.addCell(createCell("序号"));
                table.addCell(createCell("内容"));
                int i = 0;
                // 添加数据行
                for (String value : question.getValue()) {
                    i++;
                    String j = String.valueOf(i);
                    JSONObject json = new JSONObject(value);
                    table.addCell(createCell(j));
                    table.addCell(createCell(json.getString("content")));
                }
            }else{
                if(allQuestionMapper.selectAllByQuestionType(question.getSubjectId()) == 4){
                    // 添加表头
                    table.addCell(createCell("评分"));
                    table.addCell(createCell("比例"));
                }
                else if(allQuestionMapper.selectAllByQuestionType(question.getSubjectId()) == 5){
                    // 添加表头
                    table.addCell(createCell("评价"));
                    table.addCell(createCell("比例"));
                }
                else{
                    // 添加表头
                    table.addCell(createCell("选项"));
                    table.addCell(createCell("比例"));
                }
                // 添加数据行
                for (String value : question.getValue()) {
                    JSONObject json = new JSONObject(value);
                    table.addCell(createCell(json.getString("optionName")));
                    table.addCell(createCell(json.getString("num")));
                }
            }
            // 将表格添加到文档中
            document.add(table);
            document.add(new Paragraph("\n")); // 添加空行
        }
        // 关闭文档
        document.close();
    }
}
